#include "pwm.h"

static void PWM_GPIO_Config(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    // 使能GPIOA时钟
    RCC_APB2PeriphClockCmd(PWM_GPIO_CLK, ENABLE);

    // 配置GPIOA0为复用推挽输出模式
    GPIO_InitStructure.GPIO_Pin = PWM_GPIO_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(PWM_GPIO_PORT, &GPIO_InitStructure);
}

static void PWM_TIM_Config(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_OCInitTypeDef TIM_OCInitStructure;

    // 使能TIM2时钟
    RCC_APB1PeriphClockCmd(PWM_TIM_CLK, ENABLE);

    // 配置TIM2时基单元
    TIM_TimeBaseStructure.TIM_Period = 100 - 1;                 // PWM频率为1KHz，周期为1ms
    TIM_TimeBaseStructure.TIM_Prescaler = 720 - 1;              // 计数频率为72M/720=100KHz
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;     // 不分频
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数模式
    TIM_TimeBaseInit(PWM_TIM, &TIM_TimeBaseStructure);

    // 配置TIM2输出比较单元
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;             // PWM模式1
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; // 使能输出
    TIM_OCInitStructure.TIM_Pulse = 0;                            // 占空比为0%
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;     // 高电平有效
    TIM_OC1Init(PWM_TIM, &TIM_OCInitStructure);

    TIM_Cmd(PWM_TIM, ENABLE);
}

void PWM_Init(void)
{
    PWM_GPIO_Config();
    PWM_TIM_Config();
}

void PWM_SetCompare(uint16_t Compare)
{
    TIM_SetCompare1(PWM_TIM, Compare);
}